package servidor;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.util.logging.Level;
import java.util.logging.Logger;
import implementaciones.interfazServidorImpl;
import java.io.*;
import javax.swing.*;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;

import util.funcionesServerPP;


public class vistaServidor extends javax.swing.JFrame {
    //Se instancia la clase conexion para poder iniciar una,
    //o eventualmente detenerla
    private conexionPP conexion   = new conexionPP();
    private conexionRE conexion_aRE= new conexionRE(); 
    public String IP;

    private hiloConsultaRut hilo;


    public vistaServidor() {
        initComponents();
        hiloConsultaRut hilo = new hiloConsultaRut();
        hilo.start();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        Servidor_PP = new javax.swing.JPanel();
        ButtonIniciar = new javax.swing.JButton();
        ButtonDetener = new javax.swing.JButton();
        jTextIP = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Servidor Partidos Políticos");

        Servidor_PP.setBorder(javax.swing.BorderFactory.createTitledBorder("Servidor Partidos Políticos"));

        ButtonIniciar.setText("Iniciar Sever");
        ButtonIniciar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                iniciarServer(evt);
            }
        });

        ButtonDetener.setText("Detener Server");
        ButtonDetener.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                detenerServer(evt);
            }
        });

        jTextIP.setText("127.0.0.1");

        jLabel1.setText("IP de Servidor Registro Electoral");

        javax.swing.GroupLayout Servidor_PPLayout = new javax.swing.GroupLayout(Servidor_PP);
        Servidor_PP.setLayout(Servidor_PPLayout);
        Servidor_PPLayout.setHorizontalGroup(
            Servidor_PPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(Servidor_PPLayout.createSequentialGroup()
                .addGroup(Servidor_PPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(Servidor_PPLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(Servidor_PPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(ButtonDetener, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                            .addComponent(ButtonIniciar, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)))
                    .addGroup(Servidor_PPLayout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(Servidor_PPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jTextIP, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        Servidor_PPLayout.setVerticalGroup(
            Servidor_PPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, Servidor_PPLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ButtonIniciar)
                .addGap(18, 18, 18)
                .addComponent(ButtonDetener)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Servidor_PP, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Servidor_PP, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void iniciarServer(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_iniciarServer
        Registry registro;
        this.IP= this.jTextIP.getText().trim();
        System.out.println(this.IP);
        
       try {
         if(conexion_aRE.iniciarRegistry(this.IP)){ 
            registro= conexion.getRegistry();
            //Se instancia el objeto que implementa la interfaz del Servidor
            //Ahora hay que hacerlo remoto, para ello se registra en el Registry
            //con el método "rebind" que lo registra con un nombre para poder ser visto en ese espacio
            //en este caso se le dio el nombre "Implementacion".
            interfazServidorImpl objeto = new interfazServidorImpl(this.IP);
            registro.rebind("Implementacion", objeto);
            objeto.cargarRegistrados();
            this.ButtonIniciar.setEnabled(false);
            
            }
       else{
          JOptionPane.showMessageDialog(this, "Debe iniciar primero servidor RE.", "Error.", JOptionPane.ERROR_MESSAGE);
            }
       } catch (RemoteException ex) {
            Logger.getLogger(vistaServidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_iniciarServer

    private void detenerServer(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_detenerServer
        try {
            conexion.detener();
            this.ButtonIniciar.setEnabled(true);
        } catch (RemoteException ex) {
            Logger.getLogger(vistaServidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_detenerServer
 public class hiloConsultaRut extends Thread {

        private DatagramSocket socket;
        private Socket s;
        private ServerSocket ss;
        private funcionesServerPP helper= new funcionesServerPP();
        String msje_enviado=null;
        
        public void run() {
            while (true) {
                   
                try {
                    System.out.println("A la escucha");
                    ss = new ServerSocket( 10001);
                    s = ss.accept();
                    System.out.println("Client Accepted");
                    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    String[] contenido= br.readLine().split(",");
                   
                    if(contenido.length==3){
                    System.out.println(contenido[1]);
                    System.out.println(contenido[2]);
                    
                    if(contenido[0].equals("validar")){
                    String rut= contenido[1];
                    String partido=contenido[2];
                    //Esta es la funcion comprueba si la persona con ese rut esta en el partido
                    msje_enviado=  helper.comprobar(rut,partido);
                    }
                    }
                    else{
                    msje_enviado="Error de formato";
                    }
                    
                    //Envío mensaje
                    PrintWriter wr = new PrintWriter(new OutputStreamWriter(s.getOutputStream()), true);
                    wr.println(msje_enviado);

                    ss.close();
                    s.close();
                } catch (Exception e) {
                    System.out.println(e);
                    

                }

            }
          
        }
     }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonDetener;
    private javax.swing.JButton ButtonIniciar;
    private javax.swing.JPanel Servidor_PP;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextIP;
    // End of variables declaration//GEN-END:variables

}
